package org.xinjiang.data.migration.common.error;

import org.apache.commons.lang3.ArrayUtils;
import org.xinjiang.data.migration.common.error.exception.ErrorResponseException;
import org.xinjiang.data.migration.common.i18n.I18nHelp;
import org.xinjiang.data.migration.common.response.Result;

/**
 * 错误信息接口
 *
 * @author wenjie
 * @date 2022/11/25
 */
public interface ErrorDetail {

    static ErrorDetail with(int code) {
        return with(code, null);
    }

    static ErrorDetail with(int code, String message) {
        return with(code, message, null);
    }

    static ErrorDetail with(int code, String message, Object[] args) {
        return with(code, message, args, null, null);
    }

    static ErrorDetail with(int code, String message, Object data) {
        return with(code, message, null, data, null);
    }

    static ErrorDetail with(int code, String message, Object[] args, Object data) {
        return with(code, message, args, data, null);
    }

    static ErrorDetail with(int code, String message, Object data, String path) {
        return with(code, message, null, data, path);
    }

    static ErrorDetail with(int code, String message, Object[] args, Object data, String path) {
        String msg;
        if (ArrayUtils.isEmpty(args)) {
            msg = I18nHelp.message(message, args);
        } else {
            msg = I18nHelp.message(message);
        }
        return new ErrorInfo(code, msg, data, path);
    }

    int getCode();

    String getMsg();

    Object getData();

    String getPath();

    default ErrorDetail withCode(int code) {
        return with(code);
    }

    default ErrorDetail withData(Object data) {
        return with(getCode(), getMsg(), data, getPath());
    }

    default ErrorDetail withMessage(String message, Object... args) {
        String msg = I18nHelp.message(message, args);
        return with(getCode(), msg, getData(), getPath());
    }

    default ErrorDetail withPath(String path) {
        return with(getCode(), getMsg(), getData(), path);
    }

    default ErrorResponseException asException() {
        return new ErrorResponseException(this);
    }

    default ErrorResponseException asException(String message, Object... args) {
        return withMessage(message, args).asException();
    }

    default <T> Result<T> asResult() {
        return Result.fail(getCode(), getMsg(), null, getPath());
    }

    default ErrorDetail check(boolean condition, String message, Object... args) {
        if (!condition) {
            throw asException(message, args);
        }
        return this;
    }

    default ErrorDetail check(boolean condition) {
        if (!condition) {
            throw asException();
        }
        return this;
    }
}
